import requests
from collections import defaultdict
from datetime import datetime, timedelta
import re

def get_month_ago():
    today = datetime.now()
    month_ago = today - timedelta(days=30)
    return month_ago

month_ago = get_month_ago()
# 构造时间字符串
month_ago_str = month_ago.strftime('%Y-%m-%dT00:00:00+08:00')

def escape_markdown(text):
    """转义markdown中的特殊字符"""
    if not text:
        return ''
    # 需要转义的字符：\ ` * _ { } [ ] ( ) # + - . !
    special_chars = ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!']
    escaped_text = text
    for char in special_chars:
        escaped_text = escaped_text.replace(char, '\\' + char)
    return escaped_text

def process_sig_groups(api_data):
    grouped_repos = defaultdict(list)
    
    for group in api_data:
        mailing_list = group.get('mailing_list','')
        sig_name = mailing_list.split('@')[0] if '@' in mailing_list else group['sig_name']

        for repo in group.get('repos',[]):
            clean_repo = repo.strip().replace(' ','')
            if '/' not in clean_repo:
                continue
            _,repo_name = clean_repo.split('/', 1)

            if repo_name not in grouped_repos[sig_name]:
                grouped_repos[sig_name].append(repo_name)
    return dict(grouped_repos)


def fetch_and_process():
    api_url = "https://openUBMC.cn/api-dsapi/query/sig/info"

    try:
        response = requests.get(
            api_url,
            params={"community" : "openubmc"},
            verify=False,
            timeout=10
        )
        response.raise_for_status()
        
        if response.json().get('code') != 200:
            raise ValueError("状态码异常")
        
        return process_sig_groups(response.json()['data'])
    
    except Exception as e:
        print(f"数据处理失败")
        return {}
    
sig_repos = fetch_and_process()

def fetch_long_time_issues(sig_repos, month_ago_str):
    result = defaultdict(dict)
    for sig_name, repos in sig_repos.items():
        sig_issues = {}
        for repo in repos:
            url = f"https://api.gitcode.com/api/v5/repos/openUBMC/{repo}/issues"
            params = {
                "access_token": "ah11z3XPsv4z-PDxFpnHTWBr",
                "state": "open",
                "created_before": month_ago_str
            }
            try:
                response = requests.get(
                    url,
                    headers={'Accept': 'application/json'},
                    params=params,
                    timeout=10
                )
                response.raise_for_status()
                issues = response.json()
                sig_issues[repo] = {
                    'count': len(issues),
                    'issues': issues
                }
            except requests.exceptions.RequestException as e:
                print("请求失败:")
                print({str(e)})
            except ValueError as e:
                print('不合法的json响应')
        result[sig_name] = sig_issues
    return dict(result)

long_time_issues_data = fetch_long_time_issues(sig_repos, month_ago_str)

def format_md_date(dt_str):
    if not dt_str:
        return ''
    try:
        # 兼容ISO格式
        dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
        return dt.strftime('%m-%d')
    except Exception:
        return dt_str[:10] if '-' in dt_str else dt_str

with open("长时间未关闭issue.md", "w", encoding="utf-8") as f:
    for sig_name in sorted(long_time_issues_data.keys()):
        # 一级标题
        f.write(f"\n# {sig_name}组\n")
        long_time_repos = long_time_issues_data.get(sig_name, {})
        total_long_time = sum(len(repo_data.get('issues', [])) for repo_data in long_time_repos.values() if isinstance(repo_data, dict))
        if total_long_time > 0:
            f.write(f"共{total_long_time}个issue\n")
            f.write("|代码仓名称|issue标题|创建时间|创建者|指派人|\n|-----|-----|-----|-----|-----|\n")
            for repo_name, repo_data in long_time_repos.items():
                if not isinstance(repo_data, dict):
                    continue
                for idx, issue in enumerate(repo_data.get('issues', [])):
                    repo_cell = repo_name if idx == 0 else ""
                    title = escape_markdown(issue.get('title', '无标题'))
                    url = issue.get('html_url', '#')
                    created_time = format_md_date(issue.get('created_at', ''))
                    creator = issue.get('user', {}).get('login', '')
                    assignee = issue.get('assignee', {}).get('login', '') if issue.get('assignee') else ''
                    f.write(f"|{repo_cell}|[{title}]({url})|{created_time}|{creator}|{assignee}\n")
        else:
            f.write(f"sig组-{sig_name}没有一个月前创建且未关闭的issue\n")

print("报告已生成到 长时间未关闭issue.md 文件")




